import React, { PureComponent, Fragment } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Input, Popconfirm, Divider, Select, message } from 'antd';
import { TableC, PrimaryC } from '../../../../comps';
import uuid from 'es6-uuid';
import { generateSelect, showValue } from '../../../PortfolioManagement/utils';

const checkMap = {
  0: ['account-托管账户', 'name-账户名称'],
  1: ['account-资金账户', 'name-账户名称'],
  2: ['institution-市场', 'account-股东账户', 'seat-席位'],
};

export default class ExtensionList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: props.value,
      loading: false,
    };
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      this.setState({
        data: nextProps.value,
      });
    }
  }

  getRowByKey(key, newData) {
    return (newData || this.state.data).filter((item) => item.key === key)[0];
  }
  index = 0;
  cacheOriginData = {};
  toggleEditable = (e, key) => {
    e.preventDefault();
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        this.cacheOriginData[key] = { ...target };
      }
      target.editable = !target.editable;
      this.setState({ data: newData });
      setTimeout(() => {
        this.props.onChange(this.state.data);
      }, 10);
    }
  };

  remove(key) {
    const newData = this.state.data.filter((item) => item.key !== key);
    this.setState({ data: newData });
    this.props.onChange(newData);
  }
  newMember = () => {
    const { type } = this.props;
    let statedata = this.state.data ? this.state.data : [];
    const newData = statedata.map((item) => ({ ...item }));
    const account = {
      id: uuid(32),
      key: uuid(32),
      editable: true,
      isNew: true,
      type,
    };
    newData.push(account);
    this.index += 1;
    this.setState({ data: newData });
    this.props.onChange(newData);
  };

  handleKeyPress(e, key) {
    if (e.key === 'Enter') {
      this.saveRow(e, key);
    }
  }
  handleFieldChange(e, fieldName, key) {
    if (!e) return;
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      this.setState({ data: newData });
    }
  }
  handleInstitutionChange(e, fieldName, key) {
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e;
      // 如果是上交所和深交所
      if (e === '101' || e === '105') {
        target.seat = '';
      } else {
        target.seat = '\\';
      }
      this.setState({ data: newData });
    }
  }
  saveRow = (e, key) => {
    const { type } = this.props;
    e.persist();
    if (this.clickedCancel) {
      this.clickedCancel = false;
      return;
    }

    const target = this.getRowByKey(key) || {};
    const datas = this.state.data.filter((item) => item.id !== target.id);
    // 校验必填
    let flag = true;
    let flag1 = true;
    checkMap[type].forEach((element) => {
      const arr = element.split('-');
      if (!target[arr[0]]) {
        flag = false;
        message.error(`请填写${arr[1]}`);
      }
    });

    datas.map((item) => {
      if (item.account == target.account && target.type == 2) {
        message.warning('股东账户不能重复');
        flag1 = false;
        return;
      }
    });

    if (flag && flag1) {
      delete target.isNew;
      this.toggleEditable(e, key);
      setTimeout(() => {
        this.props.onChange(this.state.data);
      }, 1);
    }
  };

  // 生成列
  generateColumns = () => {
    const { type, dictMap, editabled } = this.props;
    const columns0 = [
      {
        title: '托管账户',
        dataIndex: 'account',
        key: 'account',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'account', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='托管账户'
              />
            );
          }
          return text;
        },
      },
      {
        title: '账户名称',
        dataIndex: 'name',
        key: 'name',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'name', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户名称'
              />
            );
          }
          return text;
        },
      },
      {
        title: '开户行',
        dataIndex: 'bank',
        key: 'bank',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'bank', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='开户行'
              />
            );
          }
          return text;
        },
      },
      {
        title: '大额支付号',
        dataIndex: 'seat',
        key: 'seat',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'seat', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='大额支付号'
              />
            );
          }
          return text;
        },
      },
    ];
    const columns1 = [
      {
        title: '资金账户',
        dataIndex: 'account',
        key: 'account',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'account', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='资金账户'
              />
            );
          }
          return text;
        },
      },
      {
        title: '账户名称',
        dataIndex: 'name',
        key: 'name',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'name', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户名称'
              />
            );
          }
          return text;
        },
      },
      {
        title: '柜台机构',
        dataIndex: 'institution',
        key: 'institution',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'institution', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='柜台机构'
              />
              // <Select style={{ width: '100%' }} onChange={e => this.handleFieldChange(e, 'institution', record.key)} value={text} placeholder="请选择">
              //   {generateSelect('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap)}
              // </Select>
            );
          }
          return text;
        },
      },
    ];
    const columns2 = [
      {
        title: '交易市场',
        dataIndex: 'exchangeCode',
        key: 'exchangeCode',
        render: (text, record) => {
          if (record.editable) {
            return (
              // <Input
              //   value={text}
              //   autoFocus
              //   onChange={e => this.handleFieldChange(e, 'institution', record.key)}
              //   onKeyPress={e => this.handleKeyPress(e, record.key)}
              //   placeholder="交易市场"
              // />
              <Select style={{ width: '100%' }} onChange={(e) => this.handleInstitutionChange(e, 'exchangeCode', record.key)} value={text} placeholder='请选择'>
                {generateSelect('MAAT_PRODUCT_ACCOUNT_EXCHANGE', dictMap)}
              </Select>
            );
          }
          // return text;
          return showValue('MAAT_PRODUCT_ACCOUNT_EXCHANGE', dictMap, text);
        },
      },
      {
        title: '股东账户',
        dataIndex: 'account',
        key: 'account',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'account', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='股东账户'
              />
            );
          }
          return text;
        },
      },
      {
        title: '席位',
        dataIndex: 'seat',
        key: 'seat',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                disabled={record.exchangeCode === '113'}
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'seat', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='席位'
              />
            );
          }
          return text;
        },
      },
      {
        dataIndex: 'institution',
        title: '柜台机构',
        key: 'institution',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'institution', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='柜台机构'
              />
              // <Select style={{ width: '100%' }} onChange={e => this.handleFieldChange(e, 'institution', record.key)} value={text} placeholder="请选择">
              //   {generateSelect('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap)}
              // </Select>
            );
          }
          return text;
          // return showValue('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap, text);
        },
      },
    ];
    let columns = [];
    if (type === '0') columns = columns0;
    if (type === '1') columns = columns1;
    if (type === '2') columns = columns2;
    if (!editabled) {
      columns.push({
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        render: (text, record) => {
          if (!!record.editable && this.state.loading) {
            return '\\';
          }
          if (record.editable) {
            if (record.isNew) {
              return (
                <span>
                  <a onClick={(e) => this.saveRow(e, record.key)}>添加</a>
                  <Popconfirm title='确定删除？' icon={<ExclamationCircleOutlined />} onConfirm={() => this.remove(record.key)}>
                    <a>删除</a>
                  </Popconfirm>
                </span>
              );
            }
            return (
              <span>
                <a onClick={(e) => this.saveRow(e, record.key)}>保存</a>
                <a onClick={(e) => this.cancel(e, record.key)}>取消</a>
              </span>
            );
          }
          return (
            <span>
              <a onClick={(e) => this.toggleEditable(e, record.key)}>编辑</a>
              <Popconfirm title='确定删除？' icon={<ExclamationCircleOutlined />} onConfirm={() => this.remove(record.key)}>
                <a>删除</a>
              </Popconfirm>
            </span>
          );
        },
      });
    }
    return columns;
  };
  cancel(e, key) {
    this.clickedCancel = true;
    e.preventDefault();
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (this.cacheOriginData[key]) {
      Object.assign(target, this.cacheOriginData[key]);
      target.editable = false;
      delete this.cacheOriginData[key];
    }
    this.setState({ data: newData });
    this.clickedCancel = false;
  }

  render() {
    const { type, editabled } = this.props;
    return (
      <Fragment>
        {editabled ? '' : <PrimaryC style={{ marginBottom: 16 }} onClick={this.newMember} title='新增'></PrimaryC>}
        <TableC hidePage={true} rowKey={'id'} columns={this.generateColumns()} loading={this.state.loading} dataSource={this.state.data} pagination={false} />
      </Fragment>
    );
  }
}
